package com.dao.impl;

import com.dao.ProviderDao;
import com.pojo.Provider;
import com.utils.MyRowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

@Repository
public class ProviderDaoImpl implements ProviderDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public int addProviderDao(Provider provider) {
        String sql = "insert into smbms_provider(proCode,proName,proDesc,proContact,proPhone,proAddress,proFax,createdBy,creationDate) " +
                "values(?,?,?,?,?,?,?,?,?)";
        int row = jdbcTemplate.update(sql, provider.getProCode(), provider.getProName(), provider.getProDesc(), provider.getProContact(),
                provider.getProPhone(), provider.getProAddress(), provider.getProFax(), 1, new Date());
        return row;
    }

    public int deleteProviderDao(int id) {
        String sql = "delete from smbms_provider where id=?";
        int row = jdbcTemplate.update(sql, id);
        return row;
    }

    public int updateProviderDao(Provider provider) {
        String sql = "update smbms_provider set proCode=?,proName=?,proDesc=?,proContact=?,proPhone=?," +
                "proAddress=?,proFax=?,modifyBy=?,modifyDate=? where id = ?";
        int row = jdbcTemplate.update(sql, provider.getProCode(), provider.getProName(), provider.getProDesc(), provider.getProContact(),
                provider.getProPhone(), provider.getProAddress(), provider.getProFax(), 1, new Date(),provider.getId());
        return row;
    }

    public Provider findProviderById(int id) {
        String sql = "select * from smbms_provider where id=?";
        MyRowMapper<Provider> myRowMapper = new MyRowMapper<Provider>(Provider.class);
        return jdbcTemplate.queryForObject(sql, myRowMapper, id);
    }

    public List<Provider> findAll() {
        String sql = "select * from smbms_provider";
        MyRowMapper<Provider> myRowMapper = new MyRowMapper<Provider>(Provider.class);
        return jdbcTemplate.query(sql,myRowMapper);
    }

    @Override
    public List<Provider> searchProvider(String proName) {
        String sql = "select * from smbms_provider where proName REGEXP ?";
        MyRowMapper<Provider> myRowMapper = new MyRowMapper<Provider>(Provider.class);
        return jdbcTemplate.query(sql,myRowMapper,proName);
    }
}
